#include "stdafx.h"
#include "Session.h"
#include <iostream>
#include "boost/bind.hpp"

Session::Session( boost::asio::io_service &svcIO)
:m_theSvcIO(svcIO), 
m_theSocket(svcIO), 
m_wpMsgBufferFactory(NULL), 
m_nSesId(0), 
m_nEttId(0)
{
}

int
Session::getID()const
{
	return m_nSesId;
}

void
Session::setID(int nID)
{
	m_nSesId = nID;
}

int
Session::getSID()const
{
	return m_nEttId;
}

void
Session::setSID(int nID)
{
	m_nEttId = nID;
}

boost::asio::ip::tcp::socket&
Session::getSocket()
{
	return m_theSocket;
}

bool
Session::read(MsgBuffer* pBuffer)
{
	if (pBuffer==NULL)
	{
		pBuffer = new MsgBuffer;
	}

	if (pBuffer)
	{
		m_theSocket.async_read_some(pBuffer->prepare(),
			boost::bind(&Session::onInput, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, pBuffer));
	}

	return true;
}


bool
Session::write(MsgBuffer* pBuffer)
{
	if (pBuffer)
	{
		pBuffer->update_buffer_length4();

		m_theSocket.async_write_some(pBuffer->data(),
			boost::bind(&Session::onOutput, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, pBuffer));
	}

	return true;
}

bool
Session::write(IMsg* pMsg)
{
	return false;
}

void
Session::setDataStreamPool(MsgBufferFactory* pMsgBuffFact)
{
	m_wpMsgBufferFactory = pMsgBuffFact;
}

bool
Session::onUpdate(const int& nElapse)
{
	return true;
}

void 
Session::onInput(const boost::system::error_code& error, size_t bytes_transferred, MsgBuffer* pBuffer )
{
	if (!error)
	{
		read();
	}
	else
	{
		std::cout<<"Error!"<<std::endl;
	}
}

void
Session::onOutput(const boost::system::error_code& error, size_t bytes_transferred, MsgBuffer* pBuffer )
{
	if (pBuffer)
	{
		//	recycle
		//m_wpMsgBufferFactory->free(buffer);

		delete pBuffer;
	}
}
